package jee.boot.module.websocket;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

public class WebSocketSessionManager {
    /**
     * 静态容器，记录每个客户端连接时，产生对应的ManagerWebSocket对象。
     * concurrent包的线程安全Set。
     */
    private static CopyOnWriteArraySet<SessionEntity> webSocketSessionSet = new CopyOnWriteArraySet<>();



    public static void addSession(String sid, Session session) {
        webSocketSessionSet.add(new SessionEntity(sid,session));
    }

    public static void removeSession(Session session) {
        for(SessionEntity entity:webSocketSessionSet){
            if(entity.getSession().equals(session)){
                webSocketSessionSet.remove(entity);
                break;
            }
        }
    }

    public static List<Session> getSession(String sid) {
        List<Session> list=new ArrayList<>();
        Iterator<SessionEntity> iterator = webSocketSessionSet.iterator();
        while (iterator.hasNext()){
            SessionEntity entity=iterator.next();
            if(entity.getSid().equals(sid)){
                list.add(entity.getSession());
            }else if(!entity.getSession().isOpen()){
                iterator.remove();
            }
        }

        return list;
    }

    public static List<Session> getSessions() {
        List<Session> list=new ArrayList<>();
        Iterator<SessionEntity> iterator = webSocketSessionSet.iterator();
        while (iterator.hasNext()){
            SessionEntity entity=iterator.next();
            if(entity.getSession().isOpen()){
                list.add(entity.getSession());
            }else{
                iterator.remove();
            }
        }

        return list;
    }

    static class SessionEntity {
        private String sid;
        private Session session;

        public SessionEntity(String sid, Session session) {
            this.sid = sid;
            this.session = session;
        }

        public String getSid() {
            return sid;
        }

        public void setSid(String sid) {
            this.sid = sid;
        }

        public Session getSession() {
            return session;
        }

        public void setSession(Session session) {
            this.session = session;
        }
    }
}
